<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
		<title>JQ  数据库留言板</title>
		<style type="text/css">
			.del{
				background: red;
			}
			li{
				position: relative;
			}
		</style>
	</head>
	<body>
		user <input type="text" id="use"/><br /><br />
		age <input type="text"id="ag" />
		<button id="btn">添加</button>
		<ul id="ul"></ul>
	</body>
	<script type="text/javascript">
		$.ajax({
			type:"get",
			url:"http://localhost:2403/my-objects",
			success:function(a){
				for(var i = 0;i < a.length;i++){
					create (a[i].user,a[i].age)
					var n = 1;
					var del = document.getElementsByClassName('del')
					del[i].onclick = function(){
						var delArr = document.getElementsByClassName('del')
						console.log(this)
						for (var j = 0;j < a.length;j++) {
							if(this == delArr[j]){
								de(a[j].id)
							}
						}
					}
				}
			}
		});
		//删除方法
		function  de(id){
			console.log(id);
			$.ajax({
				type:"delete",
				url:"http://localhost:2403/my-objects/" + id,
				success:function(x){
					console.log(x);
				}
			});
		}
		btn.onclick = function(){
			if(use.value == '' || ag.value == ''){
				return
			}
			var obj = {
				user:use.value,
				age:ag.value
			}
			$.ajax({
				type:"post",
				url:"http://localhost:2403/my-objects",
				data:obj,
				success:function(a){
					create (a.user,a.age)
					
				}
			});
			use.value = '';
			ag.value = ''
		}
		function create (u,a){
			var li = document.createElement('li');
			var user = document.createElement('h3');
			var age = document.createElement('p');
			var del = document.createElement('p');
			user.innerHTML = u;
			age.innerHTML = a;
			del.innerHTML = '删除';
			del.className = 'del';
			li.appendChild(user);
			li.appendChild(age);
			li.appendChild(del);
			ul.appendChild(li);
			var addBtn = document.createElement('button');
			addBtn.innerHTML = '更改';
			addBtn.className = 'addBtn';
			li.appendChild(addBtn);
			addBtn.onclick = function(id){
				var Btns  = document.getElementsByClassName('addBtn');
				var thisBtn = this;
				
				
				
				$.ajax({
					type:"get",
					url:"http://localhost:2403/my-objects",
					success:function(arr){
						for(var i = 0;i < arr.length;i++){
							if(thisBtn == Btns[i]){
								var obj = {
									user:'hahah',
									age:23
								};
								$.ajax({
									type:"put",
									url:"http://localhost:2403/my-objects/" + arr[i].id,
									data:obj,
									success:function(){
										console.log(1)
									}
								});
							}
						}
					}
				});
			}
		}
	</script>
</html>
